#
# OpenLookup - opendht.py
#
# Copyright 2008 Ken Rimey
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import time
import logging
from os import urandom
from hashlib import sha1
from binascii import hexlify, unhexlify
from xmlrpclib import Binary

from google.appengine.ext import db
from google.appengine.runtime.apiproxy_errors import OverQuotaError

from entry import Entry
from registry import register_client_application

MAX_TTL = 604800                # one week
MAX_MAXVALS = 100

class OpenDHT(object):
    """
    XML-RPC interface compatible with OpenDHT (http://opendht.org/)
    """
    def get(self, key, maxvals, placemark, application):
        log_call('get', application)
        values, placemark = self._get(key, maxvals, placemark)
        values = [v[0] for v in values]
        return [values, placemark]

    def get_details(self, key, maxvals, placemark, application):
        log_call('get_details', application)
        return self._get(key, maxvals, placemark)

    def _get(self, key, maxvals, placemark):
        key_hash = sha1(key.data).hexdigest()
        maxvals = max(1, min(MAX_MAXVALS, int(maxvals)))
        placemark = hexlify(placemark.data)
        assert len(placemark) / 2 in [0, 60, 80]

        if placemark:
            anchor, mark = placemark[:80], placemark[80:]
        else:
            anchor = mark = hexlify(urandom(40))

        results = []
        now = int(time.time())
        for entry in cyclic_query(key_hash, anchor, mark):
            ttl = entry.expiration - now
            if ttl > 0:
                lastmark = entry.placemark
                secret_hash = lastmark[40:]
                hash_type = 'SHA' if secret_hash else ''
                results.append([Binary(entry.value),
                                ttl,
                                hash_type,
                                Binary(unhexlify(secret_hash))])
                if len(results) == maxvals:
                    if lastmark == anchor:
                        break   # ridiculous border case
                    return [results, Binary(unhexlify(anchor + lastmark))]

        return [results, Binary('')]

    def put(self, key, value, ttl, application):
        log_call('put', application)
        return self._put(key, value, Binary(''), ttl)

    def put_removable(self, key, value, hash_type, secret_hash, ttl, application):
        log_call('put_removable', application)

        if hash_type not in ['', 'SHA']:
            raise ValueError('Unrecognized hash type.')

        return self._put(key, value, secret_hash, ttl)

    def _put(self, key, value, secret_hash, ttl):
        self.clean()

        key_hash = sha1(key.data).hexdigest()
        value = value.data
        value_hash = sha1(value).hexdigest()
        secret_hash = hexlify(secret_hash.data)

        ttl = max(0, min(MAX_TTL, int(ttl)))
        now = int(time.time())
        expiration = now + ttl

        query = Entry.all()
        query.filter('key_hash =', key_hash)
        query.filter('placemark =', value_hash + secret_hash)

        entry = query.get()
        if not entry:
            entry = Entry(key_hash = key_hash,
                          value = value,
                          placemark = value_hash + secret_hash,
                          expiration = expiration)

            logging.info('Creating new entry.')
            return self._put_entry(entry)
        else:
            def update_entry(db_key):
                entry = db.get(db_key)
                entry.expiration = max(expiration, entry.expiration)
                return self._put_entry(entry)

            logging.info('Updating TTL of existing entry.')
            return db.run_in_transaction(update_entry, entry.key())

    def _put_entry(self, entry):
        try:
            entry.put()
            return 0
        except OverQuotaError, message:
            logging.error(message)
            return 1

    def rm(self, key, value_hash, hash_type, secret, ttl, application):
        log_call('rm', application)

        key_hash = sha1(key.data).hexdigest()
        value_hash = hexlify(value_hash.data)

        secret = secret.data
        if hash_type == 'SHA':
            secret_hash = sha1(secret).hexdigest()
        else:
            raise ValueError('Unrecognized hash type.')

        query = Entry.all()
        query.filter('key_hash =', key_hash)
        query.filter('placemark =', value_hash + secret_hash)

        entry = query.get()
        if not entry:
            logging.info('No such entry.')
            return 2
        else:
            logging.info('Deleting entry.')
            try:
                entry.delete()
            except db.Error:
                pass
            return 0

    def clean(self):
        now = int(time.time())

        query = Entry.all()
        query.filter('expiration <', now)
        query.order('expiration')

        entries = query.fetch(20)
        if entries:
            logging.info('Clearing %d expired entries.', len(entries))
            for entry in entries:
                try:
                    entry.delete()
                except db.Error:
                    pass

        return 0

def cyclic_query(key_hash, anchor, mark):
    if mark >= anchor:
        query1 = Entry.all()
        query1.filter('key_hash =', key_hash)
        query1.filter('placemark >', mark)
        query1.order('placemark')
        for entry in query1:
            yield entry
        mark = ''

    query2 = Entry.all()
    query2.filter('key_hash =', key_hash)
    query2.filter('placemark >', mark)
    query2.filter('placemark <=', anchor)
    query2.order('placemark')
    for entry in query2:
        yield entry

def log_call(method, application):
    register_client_application(application)
    logging.info('Received %s request from %s.', method.upper(), application)
